package com.wshl.aijiuunion.controller.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.wshl.aijiuunion.GlobConstant;
import com.wshl.aijiuunion.R;
import com.wshl.aijiuunion.utils.BdLocationUtil;
import com.wshl.aijiuunion.utils.DialogUtil;
import com.wshl.aijiuunion.view.widget.NofastClickTextview;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created buy 风凊扬 on 2019/10/28 0028
 */
public class LocationActivity extends AppCompatActivity implements DialogUtil.OnBottomDilogClick {
    @BindView(R.id.mmapview)
    MapView mMapView;
    @BindView(R.id.tv_store_name)
    TextView tvStoreName;
    @BindView(R.id.tv_store_address)
    TextView tvStoreAddress;
    @BindView(R.id.tv_load)
    NofastClickTextview tvLoad;
    private BaiduMap mBaiduMap;
    private BitmapDescriptor mCurrentMarker;
    private MyLocationConfiguration.LocationMode mCurrentMode;
    private BdLocationUtil mLocationClient;
    private String latitude;
    private String lngtitude;
    private String address;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
        ButterKnife.bind(this);
        ImmersionBar.with(this)
                .init();
        Intent intent = getIntent();
        if (intent == null) {

            return;
        }

        latitude = intent.getStringExtra("lat");
        lngtitude = intent.getStringExtra("lng");
        //后台提供数据是腾讯地图坐标,这里转成百度坐标
        LatLng latLng = map_tx2bd(Double.parseDouble(latitude), Double.parseDouble(lngtitude));
        latitude = latLng.latitude + "";
        lngtitude = latLng.longitude + "";

        address = intent.getStringExtra("address");
        String name = intent.getStringExtra("name");

        tvStoreName.setText(name);
        tvStoreAddress.setText(address);
        DialogUtil.setOnBottomDilogClick(this);
        initMap();

        //获取定位
        // getLocation(this);
    }

    private void initMap() {
        mMapView.showZoomControls(false);//缩放按钮不可见
        //获取百度地图
        mBaiduMap = mMapView.getMap();
        UiSettings mUisettings = mBaiduMap.getUiSettings();
        mUisettings.setOverlookingGesturesEnabled(false);//禁止地图俯视
        mUisettings.setRotateGesturesEnabled(false);//禁止地图旋转

        //地图类型MAP_TYPE_NORMAL 	普通地图（包含3D地图）
        //MAP_TYPE_SATELLITE 	卫星图
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);

        //设置地图缩放比例
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(18.0f);
        mBaiduMap.setMapStatus(msu);
        mMapView.removeViewAt(1);//清除百度地图标识
        //自定义marker图标
        mCurrentMarker = BitmapDescriptorFactory
                .fromResource(R.drawable.weizhi);

        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);


        if (!TextUtils.isEmpty(latitude) && !TextUtils.isEmpty(lngtitude)) {
            setMaker(Double.parseDouble(lngtitude), Double.parseDouble(latitude));
            moveTocenter2(Double.parseDouble(lngtitude), Double.parseDouble(latitude));
        }

    }

    //百度地图定位
    private BdLocationUtil.MyLocationListener mLocationlistener = new BdLocationUtil.MyLocationListener() {
        @Override
        public void myLocation(BDLocation bdLocation) {
            LogUtils.i("经纬度:" + bdLocation.getLongitude() + "," + bdLocation.getLatitude());
            LogUtils.i("定位地址:" + bdLocation.getAddrStr() + bdLocation.getStreet());
            //显示详细地址
            tvStoreAddress.setText(bdLocation.getLocationDescribe() + bdLocation.getStreetNumber());
            //设置精度圈
            MyLocationData locationData = new MyLocationData.Builder()
                    .accuracy(bdLocation.getRadius())
                    .direction(bdLocation.getDirection())
                    .latitude(bdLocation.getLatitude())
                    .longitude(bdLocation.getLongitude()).build();
            //设置定位数据
            mBaiduMap.setMyLocationData(locationData);
            BitmapDescriptor locationmarker = BitmapDescriptorFactory
                    .fromResource(R.drawable.weizhi);
            mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;//定位正常态
            // 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标),精度颜色设置(这里设置成透明的颜色,是为了不让他显示精度圈)
            MyLocationConfiguration config = new MyLocationConfiguration(mCurrentMode, true, locationmarker, 0x00000000, 0x00000000);
            mBaiduMap.setMyLocationConfiguration(config);
//            //移动到地图中心
            moveTocenter2(bdLocation.getLongitude(), bdLocation.getLatitude());

        }
    };


    //获取经纬度
    private void getLocation(final Activity context) {
        XXPermissions.with(context)
                .constantRequest() //设置被拒绝后继续申请，直到用户授权或者永久拒绝
                // .permission(Permission.SYSTEM_ALERT_WINDOW, Permission.REQUEST_INSTALL_PACKAGES) //支持请求6.0悬浮窗权限8.0请求安装权限
                .permission(Permission.Group.LOCATION, Permission.Group.STORAGE) //不指定权限则自动获取清单中的危险权限
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {

                        BdLocationUtil.getInstance().requestLocation(mLocationlistener);

                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        //如果权限被永久禁止,quick值为true
                        //让用户手动打开权限设置
                        if (quick) {
                            DialogUtil.showNormaldialog(context, "请打开定位权限", false, true);
                            DialogUtil.setOndialgConfirm(new DialogUtil.OnDialogConfirm() {
                                @Override
                                public void setConfirm() {
                                    XXPermissions.gotoPermissionSettings(context);
                                }

                                @Override
                                public void setCancel() {
                                    context.finish();

                                }

                                @Override
                                public void getInput(String input) {

                                }
                            });

                        }

                    }
                });
    }

    //将当前位置移动到地图中心(不需要转换坐标)
    private void moveTocenter2(double longitude, double latitude) {
        //将该位置移动到地图中心
        LatLng ll = new LatLng(latitude, longitude);
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
        mBaiduMap.animateMapStatus(u);
    }

    //在地图上添加maker标志并显示
    private void setMaker(double longitude, double latitude) {
        // 定义Maker坐标点
        LatLng point = new LatLng(latitude, longitude);

        // LatLng transform = transform(point);//转换成百度坐标
        //BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromView(markview);
        // 构建MarkerOption，用于在地图上添加Marker
        MarkerOptions options = new MarkerOptions().position(point)
                .icon(mCurrentMarker);

        // 在地图上添加Marker，并显示
        mBaiduMap.addOverlay(options);

    }


    @OnClick({R.id.tv_load, R.id.img_fanhui})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.tv_load:
                DialogUtil.showBottomDialog(LocationActivity.this, "百度地图", "高德地图", "", "#57BE6A", "#57BE6A", "");

                break;
            case R.id.img_fanhui:
                LocationActivity.this.finish();
                break;
        }

    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    /**
     * 跳转百度地图
     */
    private void goToBaiduMap(String latstore, String lonstore, String address) {
        if (!isInstalled("com.baidu.BaiduMap")) {
            ToastUtils.showShort("请先安装百度地图客户端");
            return;
        }
        //高德地图转百度地图(高德地图使用的是火星坐标)
        LatLng endPoint = GCJ2BD(new LatLng(Double.parseDouble(latstore), Double.parseDouble(lonstore)));//坐标转换
        Intent intent = new Intent();
        intent.setData(Uri.parse("baidumap://map/direction?destination=latlng:"
                + endPoint.latitude + ","
                + endPoint.longitude +
                "|name:" + address + // 终点
                "&mode=driving" + // 导航路线方式
                "&src=" + getPackageName()));
        startActivity(intent); // 启动调用
    }

    /**
     * 跳转高德地图
     */
    private void goToGaodeMap(String latstore, String lonstore, String address) {
        if (!isInstalled("com.autonavi.minimap")) {
            ToastUtils.showShort("请先安装高德地图客户端");
            return;
        }
        LatLng endPoint = new LatLng(Double.parseDouble(latstore), Double.parseDouble(lonstore));//坐标转换
        StringBuffer stringBuffer = new StringBuffer("androidamap://navi?sourceApplication=").append("amap");
        stringBuffer.append("&lat=").append(endPoint.latitude)
                .append("&lon=").append(endPoint.longitude)
                .append("&keywords=" + address)
                .append("&dev=").append(0)
                .append("&style=").append(2);
        Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(stringBuffer.toString()));
        intent.setPackage("com.autonavi.minimap");
        startActivity(intent);


    }

    /**
     * 跳转腾讯地图
     */
    private void goToTencentMap(String latstore, String lonstore) {
        if (!isInstalled("com.tencent.map")) {
            ToastUtils.showShort("请先安装腾讯地图客户端");
            return;
        }
        LatLng endPoint = BD2GCJ(new LatLng(Double.parseDouble(latstore), Double.parseDouble(lonstore)));//坐标转换
        StringBuffer stringBuffer = new StringBuffer("qqmap://map/routeplan?type=drive")
                .append("&tocoord=").append(endPoint.latitude).append(",").append(endPoint.longitude);
        //.append("&to=" + tvLifeStoreaddress.getText().toString().trim());
        Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(stringBuffer.toString()));
        startActivity(intent);
    }

    /**
     * GCJ-02 坐标转换成 BD-09 坐标
     */
    public static LatLng GCJ2BD(LatLng bd) {
        double x = bd.longitude, y = bd.latitude;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * Math.PI);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * Math.PI);
        double tempLon = z * Math.cos(theta) + 0.0065;
        double tempLat = z * Math.sin(theta) + 0.006;
        return new LatLng(tempLat, tempLon);
    }

    /**
     * BD-09 坐标转换成 GCJ-02 坐标
     */
    public static LatLng BD2GCJ(LatLng bd) {
        double x = bd.longitude - 0.0065, y = bd.latitude - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * Math.PI);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * Math.PI);

        double lng = z * Math.cos(theta);//lng
        double lat = z * Math.sin(theta);//lat
        return new LatLng(lat, lng);
    }

    /**
     * 坐标转换，腾讯地图转换成百度地图坐标
     *
     * @param lat 腾讯纬度
     * @param lon 腾讯经度
     * @return 返回结果：经度,纬度
     */
    public static LatLng map_tx2bd(double lat, double lon) {
        double bd_lat;
        double bd_lon;
        double x_pi = 3.14159265358979324;
        double x = lon, y = lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        bd_lon = z * Math.cos(theta) + 0.0065;
        bd_lat = z * Math.sin(theta) + 0.006;
        return new LatLng(bd_lat, bd_lon);
        // return bd_lon + "," + bd_lat;
    }

    /**
     * 检测程序是否安装
     *
     * @param packageName
     * @return
     */
    private boolean isInstalled(String packageName) {
        PackageManager manager = getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> installedPackages = manager.getInstalledPackages(0);
        if (installedPackages != null) {
            for (PackageInfo info : installedPackages) {
                if (info.packageName.equals(packageName))
                    return true;
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {

        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }

    @Override
    public void setTitle1(String title) {
        goToBaiduMap(latitude, lngtitude, address);
    }

    @Override
    public void setTitle2(String title) {
        goToGaodeMap(latitude, lngtitude, address);
    }

    @Override
    public void setTitle3(String title) {

    }
}
